package com.martian.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.martian.common.enums.BaseErrorCodeEnum;
import com.martian.common.exception.SysException;

/**
 * @author martian
 * @version V1.0.0
 * @Description
 * @date 2023-03-24 14:38
 */

public class JsonUtil {
    /**
     * 对象转换为JSON
     * @param o
     * @return
     */
    public static String toJson(Object o) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return o instanceof String ? o.toString() : objectMapper.writeValueAsString(o);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException(BaseErrorCodeEnum.JSON_TRANS_ERROR);
        }
    }

    /**
     * JSON转换为对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static<T> T toObject(String json, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //objectMapper.readValue(json, clazz) 将字符串类型的JSON数据转换为对应clazz类的对象
            return clazz.equals(String.class) ? (T) json : objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException(BaseErrorCodeEnum.JSON_TRANS_ERROR);
        }
    }
}
